<div id="formDiv"></div>
<script type="text/html" id="warehouseProductionOrderformContent">
    <form lay-filter="warehouseProductionOrderForm" id="warehouseProductionOrderForm" class="layui-form open-form">
        <div class="open-model">
            <div class="open-auto">

                <table class="layui-table" id="lookDataForm" lay-filter="lookDataForm">
                    <thead>
                    <tr>
                        <!--            <th lay-data="{field:'materialNumber', width:150, sort: true, fixed: 'left'}">-->
                        <!--              加工订单编号-->
                        <!--            </th>-->
                        <th lay-data="{field:'processingType', width:150, sort: true, fixed: 'left'}">加工方式
                        </th>
                        <th lay-data="{field:'customerId', width:150, sort: true, fixed: 'left'}">客户
                        </th>

<!--                        <th lay-data="{field:'productVarietyId', width:150, sort: true, fixed: 'left'}">品种-->
<!--                        </th>-->
<!--                        <th lay-data="{field:'productMarkIdproductMarkId', width:150, sort: true, fixed: 'left'}">牌号-->
<!--                        </th>-->
<!--                        <th lay-data="{field:'productProducerId', width:150, sort: true, fixed: 'left'}">生产商-->
<!--                        </th>-->

                        <th lay-data="{field:'ownerOrderNumber', width:150, sort: true, fixed: 'left'}">货主订单号</th>
                        <th lay-data="{field:'deliveryTime', width:150, sort: true, fixed: 'left'}">交货时间</th>
                        <th lay-data="{field:'contractId', width:150, sort: true, fixed: 'left'}">所属合同</th>
                        <th lay-data="{field:'contractId', width:150, sort: true, fixed: 'left'}">原始捆包号</th>
                        <th lay-data="{field:'materialType', width:150, sort: true, fixed: 'left'}">加工重量</th>
                        <th lay-data="{field:'totalWeight', width:150, sort: true, fixed: 'left'}">总加工费</th>
                        <th lay-data="{field:'totalProcessingFee', width:150, sort: true, fixed: 'left'}">尾料</th>
                        {{# if(d.eventName === 'detail'){ }}
                        <th lay-data="{field:'creatorName', width:150, sort: true, fixed: 'left'}">创建人</th>
                        <th lay-data="{field:'createTime', width:150, sort: true, fixed: 'left'}">创建时间</th>
                        <th lay-data="{field:'createTime', width:150, sort: true, fixed: 'left'}">操作</th>
                        {{# } }}

                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <!--            <td>-->
                        <!--              <select id="computerPracticeCode" name="computerPracticeCode"-->
                        <!--                      lay-filter="computerPracticeCode"></select>-->
                        <!--            </td>-->
                        <td>
                            <select id="processingType" name="processingType" lay-filter="processingType"  lay-search required></select>
                        </td>
                        <td>
                            <select id="customerId" name="customerId" lay-filter="customerId"  lay-search required></select>
                        </td>
<!--                        <td>-->
<!--                            <select id="productVarietyId" name="productVarietyId" lay-filter="productVarietyId"  lay-search required></select>-->
<!--                        </td>-->
<!--                        <td>-->
<!--                            <select id="productMarkId" name="productMarkId" lay-filter="productMarkId"  lay-search required></select>-->
<!--                        </td>-->
<!--                        <td>-->
<!--                            <select id="productProducerId" name="productProducerId" lay-filter="productProducerId"  lay-search required></select>-->
<!--                        </td>-->

                        <td>
                            <input type="text" class="layui-input" name="ownerOrderNumber"/>
                        </td>
                        <td>
                            <input type="text" class="layui-input" id="deliveryTime" name="deliveryTime"/>
                        </td>
                        <td>
                            <select id="contractId" name="contractId" lay-filter="contractId"  lay-search required></select>
                        </td>
                        <td>
                            <input class="layui-input adv-disable" id="warehouseProductInventorId"  type="hidden" lay-filter="warehouseProductInventorId" name="warehouseProductInventorId"/>
                            <input class="layui-input adv-disable" id="userBundleCode"  lay-filter="userBundleCode" name="userBundleCode"/>
                        </td>
                        <td>
                            <input class="layui-input adv-disable" id="totalWeight" disabled
                                   name="totalWeight"/>
                        </td>
                        <td>
                            <input class="layui-input adv-disable" id="totalProcessingFee" disabled name="totalProcessingFee"/>
                        </td>
                        <td>
                            <input class="layui-input adv-disable" id="materialType" disabled name="materialType"/>
                        </td>
                        {{# if(d.eventName === 'detail'){ }}
                        <td>
                            <input class="layui-input adv-disable" id="creatorName" disabled name="creatorName"/>
                            <!--              <input type="text" class="layui-input adv-disable" id="creatorName" disabled name="creatorName" />-->
                        </td>
                        <td>
                            <input type="text" class="layui-input" id="createTime" disabled name="createTime"/>
                        </td>
                        <td>

                            <div class="" style="display: flex;align-items: center">

                                {{# if(d.status ==8){ }}
                                <button class="layui-btn layui-btn-xs layui-btn" lay-event="detail">无操作</button>
                                {{# } }}
                                {{# if(d.status == 1){ }}
                                <button class="layui-btn layui-btn-warm layui-btn-xs" id="acceptOrder">受理</button>
                                {{# } }}
                                {{# if(d.status != 8){ }}
                                <button class="layui-btn layui-btn-danger layui-btn-xs" id="terminateOrder">终止
                                </button>
                                {{# } }}
                            </div>
                        </td>
                        {{# } }}


                    </tr>
                    </tbody>
                </table>
                {{# if(d.eventName !== 'detail'){ }}
                <div class="layui-form-item tableContent" id="table" style="overflow: visible;">
                    <label class="layui-form-label" style="text-align: left;width: 140px">母卷信息：</label>
                    <table class="layui-table" id="materialNumberFormTable" lay-filter="materialNumberFormTable"></table>
                </div>
                {{# } }}

                <div class="layui-form-item tableContent" id="form">
                    <!-- {{# if(d.eventName !== 'detail'){ }} -->
                    <button class="layui-btn" type="button" id="Configure">添加成品信息</button>
                    <!-- {{# } }} -->
                    {{# if(d.eventName === 'detail'){ }}
                    <label class="layui-form-label" style="text-align: left;width: 140px">成品信息：</label>
                    {{# } }}
                    <table class="layui-table" id="purchasePlanFormTable" lay-filter="purchasePlanFormTable"></table>
                </div>

                <div class="layui-form-item tableContent" id="table"  style="overflow: visible;">
                    <!-- {{# if(d.eventName !== 'detail'){ }} -->
                    <button class="layui-btn" type="button" id="addWarehouseProcessingDescription">添加加工工艺描述模板</button>
                    <!-- {{# } }} -->
                     {{# if(d.eventName === 'detail'){ }}
                    <label class="layui-form-label" style="text-align: left;width: 140px">加工工艺描述模板：</label>
                     {{# } }}
                    <table class="layui-table" id="warehouseProcessingDescription" lay-filter="warehouseProcessingDescription"></table>
                </div>
                <div class="layui-form-item text-right">
                    <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
                    <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
                </div>
            </div>
        </div>
    </form>
</script>


<script type="text/html" id="purchasePlanFormTableBar">
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>
<script type="text/html" id="warehouseProcessingDescriptionBar">
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="warehouseProcessingDescriptiondel" type="button">删除</button>
</script>



<script type="text/html" id="customerSku">
    <div class="open-form">
        <div class="open-model">
            <div class="open-auto">
                <button class="layui-btn " id="addCustomerSku">确认选择</button>
                <button class="layui-btn " id="AddwarehouseProductBtn"><i class="layui-icon">&#xe654;</i>新增产品</button>

                <!-- 头部操作栏 -->
                <div class="layui-form" id="layuiFormSearch" style="margin-top: 20px;">
                    <div class="toolbar">
                        <div class="layui-form-item ">
                            <div class="lay-query-box" style="display: flex;align-items: center;">
                                <div class="query-lt" >
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <input name="productCode" class="layui-input" type="text"
                                                   placeholder="请输入料号"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <input name="productName" class="layui-input" type="text"
                                                   placeholder="请输入名称"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <input name="productSpecCode" class="layui-input" type="text"
                                                   placeholder="客户规格码"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productTypeIdSearch" name="productTypeName" lay-filter="productTypeId"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productVarietyIdSearch" name="productVarietyId" lay-filter="productVarietyId"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productProducerIdSearch" name="productProducerName" lay-filter="producerName"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <input type="hidden" id="productMaterialIdSearch" name="productMaterialId" placeholder="请选择材质" />
                                        <div class="layui-input-inline" id="productMaterialSearch">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productMarkIdSearch" name="productMarkName" lay-filter="productMarkId"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="query-rt">
                                    <div class="layui-inline">
                                        <button class="layui-btn icon-btn color-green" lay-filter="itemSubSearchLog"
                                                lay-submit layui-form-keyDownSearch="true">查询
                                        </button>
                                        <button class="layui-btn icon-btn color-white" lay-filter="itemResets"
                                                lay-submit>重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <table class="layui-table" id="customerSkuTable"></table>
            </div>
        </div>
    </div>
</script>

<script type="text/html" id="warehouseMaterialRequisitionRecordForm">
    <div class="open-form">
        <div class="open-model">
            <div class="open-auto">

                <div class="layui-form lay-header" style="margin-top: 20px;height: 60px">
                    <div class="toolbar">
                        <div class="layui-form-item lay-query-content">
                            <div class="lay-query-box">
                                <div class="query-lt">

                                    <div class="layui-inline">
                                        <label class="layui-form-label">品种</label>
                                        <div class="layui-input-inline mr0">
                                            <select id="productVarietyId" name="productVarietyId" lay-filter="productVarietyId"  lay-search></select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">牌号</label>
                                        <div class="layui-input-inline mr0">
                                            <select id="productMarkId" name="productMarkId" lay-filter="productMarkId"  lay-search></select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">生产商</label>
                                        <div class="layui-input-inline mr0">
                                            <select id="productProducerId" name="productProducerId" lay-filter="productProducerId"  lay-search></select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <input name="userBundleCode" class="layui-input" type="text"
                                                   placeholder="捆包号"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <input name="productCode" class="layui-input" type="text"
                                                   placeholder="客户成品料号"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <input name="productSpecCode" class="layui-input" type="text"
                                                   placeholder="客户规格码"/>
                                        </div>
                                    </div>
                                    <!-- <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productVariety" name="productVariety" lay-filter="productVariety"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productBrand" name="productBrand" lay-filter="productBrand"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productMark" name="productMark" lay-filter="productMark"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline mr0">
                                            <select id="productProducer" name="productProducer" lay-filter="productProducer"
                                                    lay-search>
                                            </select>
                                        </div>
                                    </div> -->
                                    <div class="layui-inline">
                                        <button class="layui-btn icon-btn color-green" lay-filter="itemSubSearchTwo"
                                                lay-submit layui-form-keyDownSearch="true">查询
                                        </button>
                                        <button class="layui-btn icon-btn color-white" lay-filter="itemResetsTwo"
                                                lay-submit>重置
                                        </button>
                                    </div>
                                </div>
                                <div class="query-rt"></div>
                            </div>
                        </div>
                    </div>
                </div>


                <table class="layui-table" id="warehouseMaterialRequisitionRecordTable"
                       lay-filter="warehouseMaterialRequisitionRecordTable"></table>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn" id="saveMaterialInfo" type="button" lay-submit>保存</button>
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
            </div>
        </div>
    </div>
</script>


<script>
    layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        let laydate = layui.laydate;
        let laytpl = layui.laytpl;
        const nowData = { ...parentData };
        let data = nowData?.data;
        let customerId;
        let bundleCodeCounter = 1;
        try {
            if (!data.status) {
                nowData.status = 0
            } else {
                nowData.status = data.status
            }
        } catch (e) {
            nowData.status = 0
        }
        let typeList=[{
            value: 1,
            name:'厚度'
        },{
            value: 2,
            name:'长度'
        },{
            value: 3,
            name:'包装'
        }]

        const workshopData = [{ typeName: "成品", productType: 1 }, { typeName: "余料", productType: 2 }, { typeName: "废料", productType: 3 }];
        const workshopList = workshopData.map((v) => {
            return {
                label: v.typeName,
                value: v.productType
            };
        });
        /*禁用tab键*/
        document.addEventListener('keydown', function(event) {
            if (event.keyCode === 9) { // 9是Tab键的keyCode
                event.preventDefault();
            }
        });


        let skuList = [];
        laytpl(warehouseProductionOrderformContent.innerHTML).render({ ...nowData }, function (html) {
            $("#formDiv").after(html);
        });
        // 初始化日期选择
        laydate.render({
            elem: "#deliveryTime",
            type: "datetime"
        });

        // 初始化客户选择
        await admin.initDataSelectPro(
            "enterprise/sell/admin/customersInfo/list",
            { limit: 99999 },
            "customerId",
            "客户名称",
            (d) => {
                $("#contractId").empty();
                $("#contractId").val("");
                if (d.value) {
                    customerId = d.value;
                    admin.req("warehouse/warehouse/contract/list?type=3", { warehouseCustomerId: d.value }, (res) => {
                        if (res.code == 200) {
                            admin.initDataSelect(res.data, {}, "contractId", null, "合同编号", "contractName");
                        }
                    });
                }
            },
            "customerName"
        );

        await admin.initDataSelectPro(
            "enterprise/dict/admin/dictLabel/list",
            {
                limit: 99999,
                dictType: "warehouse_processingType"

            },
            "processingType",
            "加工方式",
            (d) => {
                if (d.value) {
                    let dataList = table.cache["purchasePlanFormTable"]
                    let length=dataList.length
                    if(length>0){
                        getNewTable(dataList,length)
                    }
                    processingType = d.value;
                }
            },
            "labelName"
        );
        var  searchData = {
            productVarietyId:null,
            productMarkId:null,
            processingType:null,
        }
        await admin.initDataSelectPro(
            "warehouse/warehouse/admin/productVariety/list",
            {
                limit: 99999,

            },
            "productVarietyId",
            "品种",
            (d) => {
                if (d.value) {
                    productVarietyId = d.value;
                    searchData.productVarietyId = d.value
                }else{
                    searchData.productVarietyId = null;
                }
            },
            "varietyName"
        );
        await admin.initDataSelectPro(
            "warehouse/warehouse/admin/productMark/list",
            {
                limit: 99999,

            },
            "productMarkId",
            "牌号",
            (d) => {
                if (d.value) {
                    productMarkId = d.value;
                    searchData.productMarkId = d.value;

                }else{
                    searchData.productMarkId = null;
                }
            },
            "markName"
        );

        await admin.initDataSelectPro(
            "warehouse/warehouse/admin/productProducer/list",
            {
                limit: 99999,

            },
            "productProducerId",
            "生产商",
            (d) => {
                if (d.value) {
                    processingType = d.value;
                    searchData.processingType = processingType;
                }else{
                    searchData.processingType = null;
                }
            },
            "producerName"
        );
        var skuTable
        // $("#addMaterialInfo").click(() => {
        //     admin.formOpen({
        //         area: "90%",
        //         offset: "10%",
        //         title: "配置材料信息",
        //         content: $("#customerSku").html(),
        //         success: () => {
        //             skuTable = table.render({
        //                 elem: "#customerSkuTable",
        //                 url: config.base + "warehouse/warehouse/product/list",
        //                 where: {
        //                     notIds: table.cache["warehouseMaterialRequisitionRecordTable"].map((v) => {
        //                         return v.id;
        //                     })
        //                 },
        //                 page: true,
        //                 cols: [
        //                     [
        //                         {type: "checkbox"},
        //                         {field: "productVariety", align: "center", title: "品种"},
        //                         {field: "productCode", align: "center", title: "客户成品料号"},
        //                         {field: "productSpecCode", align: "center", title: "规格"},
        //                         {field: "diameter", align: "center", title: "厚度/壁厚/直径"},
        //                         {field: "width", align: "center", title: "宽度/外径"},
        //                         {field: "length", align: "center", title: "长度"},
        //                         {field: "productMainUnit", align: "center", title: "成品单位"}
        //                     ]
        //                 ]
        //             });
        //             $("#addCustomerSku").click(function () {
        //                 console.log(parentData,"parentData")
        //                 let checkData = table.checkStatus("customerSkuTable").data; // 获取选中的数据
        //                 layer.close(nowData.zindex);
        //                 table.reload("warehouseMaterialRequisitionRecordTable", {
        //                     data: [...table.cache["warehouseMaterialRequisitionRecordTable"], ...checkData]
        //                 });
        //             });
        //             // 搜索
        //             form.on("submit(itemSubSearchLog)", function (data) {
        //                 console.log(data,"data")
        //                 skuTable.reload({
        //                     where: {
        //                         ...data.field,
        //                         notIds: table.cache["warehouseMaterialRequisitionRecordTable"].map((v) => v.id)
        //                     },
        //                     page: {curr: 1}
        //                 });
        //             });
        //
        //             // 重置搜索
        //             form.on("submit(itemResets)", function (data) {
        //                 skuTable.reload({
        //                     where: {
        //                         ...admin.resetSearch(data.field),
        //                         notIds: table.cache["warehouseMaterialRequisitionRecordTable"].map((v) => v.id)
        //                     },
        //                     page: {curr: 1}
        //                 });
        //             });
        //
        //             form.render("select");
        //         }
        //     });
        // });
        let nowIndex

        // 品种列表
        const productVarietyData = await admin.reqPro("warehouse/warehouse/product/list", { limit: 99999 });
        const productVarietyList = productVarietyData.data;

        if (nowData.eventName === "detail") {
            admin.setFormDisable("#warehouseProductionOrderForm", true);
        }





        const tableVal = table.render({
            elem: "#purchasePlanFormTable",
            page: false,
            limit: 999999,
            //   height: 400,
            data: [],
            cols: [
                [
                    { type: "numbers", title: "序号" },
                    { title: "捆包编号", field: "childBundle", },
                    {
                        field: "productType",
                        align: "center",
                        title: "捆包性质",
                        templet: function (d) {
                            return admin.setTableSelect("productType", workshopList, nowData.eventName == "detail", "productType")(d);
                        }
                    },
                    {
                        field: "productSpecCode", align: "center", title: "规格",
                        templet: admin.setTableInput("productSpecCode", nowData.eventName === "detail", "productSpecCode")
                    },
                    {
                        field: "diameter", align: "center", title: "厚度/壁厚/直径(mm)",width: 150,edit: nowData.eventName === "detail"?null:'input',
                        templet: admin.setTableInput("diameter", nowData.eventName === "detail", "diameter")
                    },
                    {
                        field: "warehouseWidth", align: "center", title: "宽度/外径(mm)",edit: nowData.eventName === "detail"?null:'input',
                        templet: admin.setTableInput("warehouseWidth", nowData.eventName === "detail", "warehouseWidth")
                    },
                    {
                        field: "warehouseLength", align: "center", title: "长度(mm)",edit: nowData.eventName === "detail"?null:'input',
                        templet: admin.setTableInput("warehouseLength", nowData.eventName === "detail", "warehouseLength")
                    },
                    // {
                    //     field: "type",
                    //     align: "center",
                    //     title: "类型",
                    //     hide: nowData.eventName === "detail",
                    //     templet: admin.setTableSelect(
                    //         "type",
                    //         [
                    //             { value: '1', label: "厚度" },
                    //             { value: '2', label: "长度" },
                    //             { value: '3', label: "包装" }
                    //         ],
                    //         nowData.eventName === "detail",
                    //         "type"
                    //     )
                    // },
                    {
                        field: "packageMethod",
                        align: "center",
                        title: "包装方式",
                        templet: admin.setTableSelect(
                            "packageMethod",
                            [
                                { value: '0', label: "一般包装" },
                                { value: '1', label: "立式包装" },
                            ],
                            nowData.eventName === "detail",
                            "packageMethod"
                        )
                    },
                    {
                        field: "productMainUnit", align: "center", title: "成品单位",
                        templet: admin.setTableInput("productMainUnit", nowData.eventName === "detail", "productMainUnit")
                    },
                    {
                        field: "bundleQuantity", align: "center", title: "捆包件数",edit: nowData.eventName === "detail"?null:'input',
                        templet: admin.setTableInput("bundleQuantity", nowData.eventName === "detail", "bundleQuantity")
                    },
                    {
                        field: "unitWeight", align: "center", title: "单位重量(吨)",
                    },
                    // {
                    //     field: "price", align: "center", title: "单位价格",
                    //     templet: admin.setTableInput("price", nowData.eventName == "detail", "price")
                    // },
                    {
                        field: "theoreticalWeight", align: "center", title: "理论重量(吨)",
                    },
                    {
                        field: "remark",
                        align: "center",
                        title: "加工备注",
                        templet: admin.setTableInput("remark", nowData.eventName === "detail", "remark")
                    },
                    {
                        field: "price",
                        align: "center",
                        title: "加工单价(吨)",
                    },
                    { title: "小计", field: "subtotal", align: "center",  },
                    {
                        align: "center",
                        toolbar: "#purchasePlanFormTableBar",
                        title: "操作",
                        width: 100,
                        hide: nowData.eventName === "detail"
                    }
                ]
            ],
            done: function () {
                var getsubtotal = function(data,index) {
                    let materialNumber= table.cache["materialNumberFormTable"];
                    let tableData= table.cache["purchasePlanFormTable"];
                    let length= tableData.length;
                    let markId=materialNumber[0].markId
                    let density=materialNumber[0].density
                    let grossWeight=materialNumber[0].grossWeight
                    let bundleQuantity=data.bundleQuantity
                    let processId=$("#processingType").val()
                    let warehouseLength=data.warehouseLength
                    let theoreticalWeight=data.theoreticalWeight
                    let packageMethod=data.packageMethod
                    let unitWeight=data.unitWeight
                    let warehouseWidth=data.warehouseWidth
                    let type=data.type
                    let diameter=data.diameter
                    let formData={markId,processId,count:length,warehouseLength,diameter}
                    if(warehouseWidth && warehouseLength && diameter && density){
                        let num=(Number(warehouseLength)*Number(warehouseWidth)*Number(diameter))/1000
                        let unitWeight=parseFloat((num*Number(density)).toFixed(4))
                        tableData[index].unitWeight=unitWeight
                        if(bundleQuantity){
                            tableData[index].theoreticalWeight=parseFloat((Number(unitWeight)*Number(bundleQuantity)).toFixed(4))
                        }
                        tableVal.reload({
                            data: tableData,
                        });

                    }
                    if(markId && processId && warehouseLength  && diameter){
                        admin.req(
                            "warehouse/warehouse/admin/productMark/computePrice",
                            formData,
                            function (res) {
                                layer.closeAll("loading");
                                if (res.code == 200) {
                                    tableData[index].newPrice=res.data
                                    tableData[index].price=res.data
                                    if(packageMethod==='1'){
                                        tableData[index].price=Number(res.data)+10
                                        if(unitWeight && bundleQuantity){
                                            let num2=Number(unitWeight)*Number(bundleQuantity)*Number(Number(res.data)+10)
                                            tableData[index].subtotal=parseFloat(num2.toFixed(4))
                                        }
                                    }else{
                                        if(unitWeight && bundleQuantity){
                                            let num2=Number(unitWeight)*Number(bundleQuantity)*Number(res.data)
                                            tableData[index].subtotal=parseFloat(num2.toFixed(4))
                                        }
                                    }
                                    tableVal.reload({
                                        data: tableData,
                                    });

                                } else {
                                    tableData[index].newPrice=0
                                    tableData[index].price=0
                                    tableData[index].subtotal=0
                                    tableVal.reload({
                                        data: tableData,
                                    });
                                    layer.msg(res.msg, { icon: 2, time: 1000 });
                                }
                            },
                            "GET",
                            false,
                            "application/json"
                        );
                    }
                    form.val("warehouseProductionOrderForm", {
                        totalProcessingFee : tableData.reduce((acc, curr) => acc + (curr.subtotal || 0), 0),
                        totalWeight: parseFloat(tableData.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0)).toFixed(4),
                        materialType: parseFloat(grossWeight-tableData.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0)).toFixed(4),
                    });
                };
                table.on('edit(purchasePlanFormTable)', function(obj){
                    var value = obj.value // 得到修改后的值
                    var data  = obj.data // 得到所在行所有键值
                    var field = obj.field; // 得到字段
                    var rowIndex = $(obj.tr).attr("data-index");
                    var update = {};
                    update[field] = value;
                    obj.update(update);
                    getsubtotal(data,rowIndex)

                });
                $("#form .layui-table-body, #form .layui-table-box,#form .layui-table-cell").css('overflow','visible');
                // const fields = [
                //     "bundleQuantity", "warehouseWidth", "productMainUnit", "requiredQuantity", "diameter","warehouseLength"
                // ];
                //
                // fields.forEach(function (field) {
                //     admin.tableInputChangeByClass("purchasePlanFormTable", field, function (index, value, tableData, field, tableId) {
                //         let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                //         if (rowIndex > -1) {
                //             // 对于数字类型字段，如 requiredQuantity 和 diameter，进行数字处理
                //             if (field === "requiredQuantity" || field === "diameter") {
                //                 tableData[rowIndex][field] = parseFloat(value) || 0; // 更新为数字，防止空值
                //             } else {
                //                 tableData[rowIndex][field] = value; // 其他字段直接更新
                //             }
                //         }
                //     });
                // });
                const fields2 = [
                     // "bundleQuantity"
                ];

                fields2.forEach(function (field) {
                    admin.tableInputChangeByClass("purchasePlanFormTable", field, function (index, value, tableData, field, tableId) {
                        let debounceTimer;
                        let materialNumber= table.cache["materialNumberFormTable"];
                        let markId=materialNumber[0].markId
                        let density=materialNumber[0].density
                        let grossWeight=materialNumber[0].grossWeight
                        let bundleQuantity=tableData[index].bundleQuantity
                        let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                        let processId=$("#processingType").val()
                        let warehouseLength=tableData[index].warehouseLength
                        let theoreticalWeight=tableData[index].theoreticalWeight
                        let packageMethod=tableData[index].packageMethod
                        let unitWeight=tableData[index].unitWeight
                        let warehouseWidth=tableData[index].warehouseWidth
                        let type=tableData[index].type
                        let diameter=tableData[index].diameter
                        let formData={markId,processId,count:tableData.length,warehouseLength,diameter}
                        if(warehouseWidth && warehouseLength && diameter && density){
                            let num=(Number(warehouseLength)*Number(warehouseWidth)*Number(diameter))/1000
                            let unitWeight=parseFloat((num*Number(density)).toFixed(4))
                            tableData[index].unitWeight=unitWeight
                            if(bundleQuantity){
                                tableData[index].theoreticalWeight=parseFloat((Number(unitWeight)*Number(bundleQuantity)).toFixed(4))
                            }
                            clearTimeout(debounceTimer);
                            debounceTimer = setTimeout(() => {
                                tableVal.reload({
                                    data: tableData,
                                });
                            }, 2000);

                        }
                        if(markId && processId && warehouseLength  && diameter){
                            admin.req(
                                "warehouse/warehouse/admin/productMark/computePrice",
                                formData,
                                function (res) {
                                    layer.closeAll("loading");
                                    if (res.code == 200) {
                                        tableData[index].newPrice=res.data
                                        tableData[index].price=res.data
                                        if(packageMethod==='1'){
                                            tableData[index].price=Number(res.data)+10
                                            if(unitWeight && bundleQuantity){
                                                let num2=Number(unitWeight)*Number(bundleQuantity)*Number(Number(res.data)+10)
                                                tableData[index].subtotal=parseFloat(num2.toFixed(4))
                                            }
                                        }else{
                                            if(unitWeight && bundleQuantity){
                                                let num2=Number(unitWeight)*Number(bundleQuantity)*Number(res.data)
                                                tableData[index].subtotal=parseFloat(num2.toFixed(4))
                                            }
                                        }
                                        clearTimeout(debounceTimer);
                                        debounceTimer = setTimeout(() => {
                                            tableVal.reload({
                                                data: tableData,
                                            });
                                        }, 2000);
                                    } else {
                                        tableData[index].newPrice=0
                                        tableData[index].price=0
                                        tableData[index].subtotal=0
                                        tableVal.reload({
                                            data: tableData,
                                        });
                                        layer.msg(res.msg, { icon: 2, time: 1000 });
                                    }
                                },
                                "GET",
                                false,
                                "application/json"
                            );
                        }
                        form.val("warehouseProductionOrderForm", {
                            totalProcessingFee : tableData.reduce((acc, curr) => acc + (curr.subtotal || 0), 0),
                            totalWeight: parseFloat(tableData.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0)).toFixed(4),
                            materialType: parseFloat(grossWeight-tableData.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0)).toFixed(4),
                        });
                    });
                });

                admin.tableSelectChange("purchasePlanFormTable", "productType", (index, value, tableData, field, tableId) => {})
                admin.tableSelectChange("purchasePlanFormTable", "packageMethod", (index, value, tableData, field, tableId) => {
                    let unitWeight=tableData[index].unitWeight
                    let bundleQuantity=tableData[index].bundleQuantity
                    if(value==='1'){
                        tableData[index].price=Number(tableData[index].newPrice)+10
                        if(unitWeight && bundleQuantity){
                            let num2=Number(unitWeight)*Number(bundleQuantity)*Number(Number(tableData[index].newPrice)+10)
                            tableData[index].subtotal=parseFloat(num2.toFixed(4))
                        }
                    }else{
                        tableData[index].price=Number(tableData[index].newPrice)
                        if(unitWeight && bundleQuantity){
                            let num2=Number(unitWeight)*Number(bundleQuantity)*Number(tableData[index].newPrice)
                            tableData[index].subtotal=parseFloat(num2.toFixed(4))
                        }
                    }
                    tableVal.reload({
                        data: tableData
                    });
                    form.val("warehouseProductionOrderForm", {
                        totalProcessingFee: tableData.reduce((acc, curr) => acc + (curr.subtotal || 0), 0),
                    });
                })
                admin.tableSelectChange("purchasePlanFormTable", "type", (index, value, tableData, field, tableId) => {
                    let materialNumber= table.cache["materialNumberFormTable"];
                    let markId=materialNumber[0].markId
                    let grossWeight=materialNumber[0].grossWeight
                    let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                    let processId=$("#processingType").val()
                    let warehouseLength=tableData[index].warehouseLength
                    let unitWeight=tableData[index].unitWeight
                    let bundleQuantity=tableData[index].bundleQuantity
                    let type=tableData[index].type
                    let packageMethod=tableData[index].packageMethod
                    let diameter=tableData[index].diameter
                    let formData={markId,processId,count:tableData.length,warehouseLength,type,diameter}
                    if(markId && processId && warehouseLength && type && diameter){
                        admin.req(
                            "warehouse/warehouse/admin/productMark/computePrice",
                            formData,
                            function (res) {
                                layer.closeAll("loading");
                                if (res.code == 200) {
                                    tableData[index].newPrice=res.data
                                    tableData[index].price=res.data
                                    if(packageMethod==='1'){
                                        tableData[index].price=Number(res.data)+10
                                        if(unitWeight && bundleQuantity){
                                            let num2=Number(unitWeight)*Number(bundleQuantity)*Number(Number(res.data)+10)
                                            tableData[index].subtotal=parseFloat(num2.toFixed(4))
                                        }
                                    }else{
                                        if(unitWeight && bundleQuantity){
                                            let num2=Number(unitWeight)*Number(bundleQuantity)*Number(res.data)
                                            tableData[index].subtotal=parseFloat(num2.toFixed(4))
                                        }
                                    }
                                    tableVal.reload({
                                        data: tableData
                                    });
                                } else {
                                    tableData[index].newPrice=0
                                    tableData[index].price=0
                                    tableData[index].subtotal=0
                                    tableVal.reload({
                                        data: tableData,
                                    });
                                    layer.msg(res.msg, { icon: 2, time: 1000 });
                                }
                            },
                            "GET",
                            false,
                            "application/json"
                        );
                    }
                    form.val("warehouseProductionOrderForm", {
                        totalProcessingFee: tableData.reduce((acc, curr) => acc + (curr.subtotal || 0), 0),
                        totalWeight: tableData.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0),
                        materialType: parseFloat(grossWeight-tableData.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0)).toFixed(4),
                    });
                });
                // 更新总计

                // 在输入框变化时，确保表格缓存数据得到更新
                admin.tableInputChangeByClass("purchasePlanFormTable", "productSpecCode", function (index, value, tableData, field, tableId) {
                    let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                    if (rowIndex > -1) {
                        tableData[rowIndex][field] = value; // 更新 productSpecCode 字段值
                    }
                });
                admin.tableInputChangeByClass("purchasePlanFormTable", "remark", () => {});
                admin.tableInputChangeByClass("purchasePlanFormTable", "productMainUnit", () => {});
                if (nowData.eventName === "detail") {
                } else {
                    // form.val("warehouseProductionOrderForm", {
                    //     materialType: table.cache["purchasePlanFormTable"].length,
                    //     totalWeight: table.cache["purchasePlanFormTable"].reduce((acc, curr) => acc + curr.netWeight * (curr.requiredQuantity || 0), 0),
                    //     totalProcessingFee: table.cache["purchasePlanFormTable"].reduce((acc, curr) => acc + curr.price * (curr.requiredQuantity || 0), 0)
                    // });
                }
                // class为requiredQuantity的限制输入数字
                $(".requiredQuantity").attr("type", "number");
                $(".price").attr("type", "number");
                upload.render({
                    elem: ".upload-btn", // 绑定上传按钮
                    url: config.upload_url + "uploadFile",
                    accept: "file", // 可接受的文件类型
                    headers: { Authorization: "Bearer " + config.getToken() },
                    done: function (res, index, upload) {
                        // 上传成功的回调
                        if (res.code === 200) {
                            // 更新表格缓存中的数据
                            const button = $(this.item);
                            const index = button.data("index");
                            let tableData = table.cache["purchasePlanFormTable"];
                            let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                            if (rowIndex > -1) {
                                tableData[rowIndex].processingDrawing = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
                                tableData[rowIndex].processingDrawingName = res.data.fileName; // 假设接口返回的文件路径是 res.data.fileUrl
                            }
                            $(`#uploaded-${index}`).html(`<a href="${res.data.url}" target="_blank">查看附件</a>`);
                            console.log("文件上传成功:", res.data);
                        } else {
                            console.error("文件上传失败:", res.message);
                        }
                    },
                    error: function () {
                        // 上传失败的回调
                        console.error("上传失败");
                    }
                });
            }
        });



        const tableVal2 = table.render({
            elem: "#warehouseProcessingDescription",
            page: false,
            limit: 999999,
            //   height: 400,
            data: [],
            cols: [
                [
                    { type: "numbers", title: "序号" },

                    {field: "processingTypeName", title: "适用工艺", align: "center"},
                    {field: "productVarietyName", title: "适用品种", align: "center"},
                    // {field: "customerLevelId", title: "客户级别", align: "center"},
                    {field: "productMarkName", title: "适用钢种", align: "center"},
                    {field: 'customerName', title: '适用客户', align: 'center'},
                    {field: "remark", title: "描述", align: "center"},
                    {
                        field: "isDeleted",
                        title: "状态",
                        align: "center",
                        templet: function (d) {
                            if(d.isDeleted){
                                return "禁用"
                            }else{
                                return "正常"
                            }
                        },
                    },
                    // {field: 'creatorName', title: '创建人' , align: 'center'},
                    // {field: "createTime", title: "添加时间", align: "center"},
                    {
                        align: "center",
                        toolbar: "#warehouseProcessingDescriptionBar",
                        title: "操作",
                        width: 100,
                        hide: nowData.eventName === "detail"
                    }
                ]
            ],
            done: function () {
            }
        });
        const tableVal3 = table.render({
            elem: "#materialNumberFormTable",
            page: false,
            limit: 999999,
            //   height: 400,
            data: [],
            cols: [
                [
                    { type: "numbers", title: "序号" },
                    { field: "userBundleCode", align: "center", title: "客户原始捆包号" },
                    { field: "productVariety", align: "center", title: "品种" },
                    { field: "productMark", align: "center", title: "牌号" },
                    { field: "productProducer", align: "center", title: "厂家" },
                    { field: "productSpecCode", align: "center", title: "规格" },
                    { field: "specThickness", align: "center", title: "厚度/壁厚/直径" },
                    { field: "specWidth", align: "center", title: "宽度/外径" },
                    { field: "specLength", align: "center", title: "长度" },
                    { field: "productMainUnit", align: "center", title: "成品单位" },
                    { field: "grossWeight", align: "center", title: "净重" },
                    { field: "netWeight", align: "center", title: "毛重" },
                    { field: "density", align: "center", title: "密度" },
                ]
            ],
            done: function () {
            }
        });
        admin.tableSelectChange("purchasePlanFormTable", "productType", (index, value, tableData, field, tableId) => {
            // 不再在这里添加新行
            tableVal.reload({
                data: tableData
            });
        });

        if (data && data.id) {
            form.val("warehouseProductionOrderForm", data);
            admin.initDataSelect(
                "warehouse/warehouse/contract/list",
                {
                    warehouseCustomerId: data.customerId
                },
                "contractId",
                data.contractId,
                "合同编号",
                "contractName"
            );
            tableVal.reload({
                data: data.warehouseProductionOrderDetailList.map(v => {
                    delete v.length
                    // delete  v.width
                    return v
                }),
            });
            tableVal2.reload({
                data: data.warehouseProcessingDescriptionList.map(v => {
                    delete v.length
                    // delete  v.width
                    return v
                }),
            });
        } else {
        }


        form.on("submit(formSubmit)", function (d) {
            let formData = { ...d.field };
            formData.warehouseProductionOrderDetailList = table.cache["purchasePlanFormTable"];
            formData.warehouseProductionOrderProcessingList = table.cache["warehouseProcessingDescription"];
            formData.warehouseProductionOrderProcessingList.forEach(item=>item.processingId=item.id)
            // 检查每个 requiredQuantity 是否大于 1
            if (formData.warehouseProductionOrderDetailList.length === 0) {
                layer.msg("必须存在产品信息", { icon: 2, time: 1000 });
                return false;
            }
            if (formData.warehouseProductionOrderDetailList.some(item => item.diameter==='' )) {
                layer.msg("请填写厚度/壁厚/直径", { icon: 2, time: 1000 });
                return false;
            }
            if (formData.warehouseProductionOrderDetailList.some(item => item.warehouseWidth==='' )) {
                layer.msg("请填写宽度/外径", { icon: 2, time: 1000 });
                return false;
            }
            if (formData.warehouseProductionOrderDetailList.some(item => item.warehouseLength==='' )) {
                layer.msg("请填写长度", { icon: 2, time: 1000 });
                return false;
            }
            if (formData.warehouseProductionOrderDetailList.some(item => item.bundleQuantity==='' )) {
                layer.msg("请填写捆包件数", { icon: 2, time: 1000 });
                return false;
            }
            // if (formData.warehouseProductionOrderDetailList.some(item => item.type==='' )) {
            //     layer.msg("已选择类型", { icon: 2, time: 1000 });
            //     return false;
            // }
            if (formData.warehouseProductionOrderDetailList.some(item => item.packageMethod==='' )) {
                layer.msg("请选择包装方式", { icon: 2, time: 1000 });
                return false;
            }
            // // 检查每个 requiredQuantity 是否大于 1
            // if (formData.warehouseProductionOrderDetailList.some(item => Number(item.price) <= 0 || !Number(item.price))) {
            //     layer.msg("已添加产品单位价格必须大于0", { icon: 2, time: 1000 });
            //     return false;
            // }
            // // 检查每个 materialNumber 是否为空
            //     if (formData.warehouseProductionOrderDetailList.some(item => !item.materialNumber)) {
            //         layer.msg("请选择物料", { icon: 2, time: 1000 });
            //         return false;
            //     }
            //
            if(formData.warehouseProductionOrderProcessingList.length === 0){
                layer.msg("请选择至少一条加工工艺描述模板", { icon: 2, time: 1000 });
                return false;
            }



            // formData.remainingProductionSchedule = formData.warehouseProductionOrderDetailList.reduce((acc, curr) => acc + Number(curr.requiredQuantity || 0), 0);
            // formData.processedQuantity = formData.remainingProductionSchedule;
            // console.log(formData.remainingProductionSchedule);
            if (nowData.eventName == "add") {
                delete formData.id;
                admin.req(
                    "warehouse/warehouse/productionOrder/add",
                    JSON.stringify(formData),
                    function (res) {
                        layer.closeAll("loading");
                        if (res.code == 200) {
                            layer.msg(res.msg, { icon: 1 });
                            table.reload("ProductionOrderTable");
                            layer.closeAll("page");
                        } else {
                            layer.msg(res.msg, { icon: 2, time: 1000 });
                        }
                    },
                    "POST",
                    false,
                    "application/json"
                );
            }
            return false;
        });
        $("#acceptOrder").click(() => {
            event.preventDefault(); // 阻止默认行为
            // 确认是否审核通过
            layer.open({
                title: "审核",
                content: "是否审核通过？",
                btn: ["审核通过", "关闭"],
                yes: (index) => {
                    console.log(index);
                    admin.req("warehouse/warehouse/productionOrder/updateProduction", {
                        id: data.id,
                        status: 2
                    }, (res) => {
                        if (res.code === 200) {
                            layer.msg("审核通过");
                            layer.close(index);
                            nowData.status = 2;
                            layer.close(parentData.zindex);
                            table.reload("ProductionOrderTable");

                        }
                    });
                }
            });
        });
        $("#terminateOrder").click(() => {
            event.preventDefault(); // 阻止默认行为
            // 确认是否审核通过
            layer.open({
                title: "审核",
                content: "是否终止该订单？",
                btn: ["终止", "关闭"],
                yes: (index) => {
                    console.log(index);
                    admin.req("warehouse/warehouse/productionOrder/updateProduction", {
                        id: data.id,
                        status: 8
                    }, (res) => {
                        if (res.code === 200) {
                            layer.msg("终止成功");
                            layer.close(index);
                            nowData.status = 8;
                            layer.close(parentData.zindex);
                            table.reload("ProductionOrderTable");
                        }
                    });
                }
            });
        });
        $("#purchasePlanSuccess").click(() => {
            const formData = nowData.data;
            formData.planInfoList = table.cache["purchasePlanFormTable"];
            formData.status = "success";
            formData.reason = $("#reason").val();
            admin.req(
                "enterprise/purchase/admin/purchasePlan/audit",
                JSON.stringify(formData),
                function (data) {
                    layer.closeAll("loading");
                    if (data.code == 200) {
                        layer.msg(data.msg, { icon: 1, time: 500 });
                        table.reload("purchasePlanTable");
                        layer.closeAll("page");
                    } else {
                        layer.msg(data.msg, { icon: 2, time: 1000 });
                    }
                },
                "POST",
                false,
                "application/json"
            );
        });
        $("#purchasePlanFail").click(() => {
            const formData = nowData.data;
            formData.planInfoList = table.cache["purchasePlanFormTable"];
            formData.status = "fail";
            formData.reason = $("#reason").val();
            admin.req(
                "enterprise/purchase/admin/purchasePlan/audit",
                JSON.stringify(formData),
                function (data) {
                    layer.closeAll("loading");
                    if (data.code == 200) {
                        layer.msg(data.msg, { icon: 1, time: 500 });
                        table.reload("purchasePlanTable");
                        layer.closeAll("page");
                    } else {
                        layer.msg(data.msg, { icon: 2, time: 1000 });
                    }
                },
                "POST",
                false,
                "application/json"
            );
        });
        $("#userBundleCode").click(function (){
            if(nowData.eventName == "detail"){
                return;
            }
            if($("#customerId").val() == ""){
                layer.msg("请选择客户", { icon: 2, time: 1000 });
                return
            }
            var tableTwo
            let zindex = admin.formOpen({
                area: "90%",
                offset: "10%",
                title: "选择物料",
                content: $("#warehouseMaterialRequisitionRecordForm").html(),
                success:async function () {
                    await admin.initDataSelectPro("warehouse/warehouse/admin/productVariety/list",{limit: 99999,},"productVarietyId","品种",null,"varietyName");
                    await admin.initDataSelectPro("warehouse/warehouse/admin/productMark/list",{limit: 99999,},"productMarkId","牌号",null,"markName");
                    await admin.initDataSelectPro("warehouse/warehouse/admin/productProducer/list",{limit: 99999,},"productProducerId","生产商",null,"producerName");
                    tableTwo = table.render({
                        elem: "#warehouseMaterialRequisitionRecordTable",
                        url: config.base + "warehouse/warehouse/productInventory/list?productStatus=3&customerId=" + customerId,
                        where:searchData,
                        page: true,
                        cols: [
                            [
                                { type: "radio" },
                                { field: "userBundleCode", align: "center", title: "捆包号" },
                                { field: "productVariety", align: "center", title: "品种" },
                                { field: "productMark", align: "center", title: "牌号" },
                                { field: "productProducer", align: "center", title: "厂家" },
                                { field: "warehouseName", align: "center", title: "所在仓库" },
                                { field: "warehouseShelfSpaceCode", align: "center", title: "所在库位" },
                                { field: "productCode", align: "center", title: "客户成品料号" },
                                { field: "productSpecCode", align: "center", title: "规格" },
                                { field: "specThickness", align: "center", title: "厚度/壁厚/直径" },
                                { field: "specWidth", align: "center", title: "宽度/外径" },
                                { field: "specLength", align: "center", title: "长度" },
                                { field: "grossWeight", align: "center", title: "重量" },
                                { field: "productMainUnit", align: "center", title: "成品单位" },
                                // { field: "grossWeight", align: "center", title: "首入库时间" },
                            ]
                        ]
                    });
                    // 搜索
                    form.on("submit(itemSubSearchTwo)", function (data) {
                        tableTwo.reload({
                            where: {
                                ...data.field,
                            },
                            page: { curr: 1 }
                        });
                    });

                    // 重置搜索
                    form.on("submit(itemResetsTwo)", function (data) {
                        tableTwo.reload({
                            where: {
                                ...admin.resetSearch(data.field),
                            },
                            page: { curr: 1 }
                        });
                    });``
                    $("#saveMaterialInfo").click(() => {
                        let list = table.cache["purchasePlanFormTable"];
                        let materialNumberCont = table.cache["materialNumberFormTable"];
                        let list1 = table.checkStatus("warehouseMaterialRequisitionRecordTable").data;
                        if(materialNumberCont[0]?.id!=list1[0].id){
                            $("#userBundleCode").val(list1[0].userBundleCode)
                            $("#warehouseProductInventorId").val(list1[0].id)
                            table.reload("materialNumberFormTable", {
                                data: list1
                            });
                            table.reload("purchasePlanFormTable", {
                                data: []
                            });
                            bundleCodeCounter=1
                        }

                        layer.close(zindex);

                    });
                }
            });
        })
        table.on("tool(purchasePlanFormTable)", function (obj) {
            var d = obj.data; // 获取当前行的数据
            var layEvent = obj.event; // 获取事件名（edit 或 del）
            if (obj.tr) {
                obj.tr.on("click", function (e) {
                    e.preventDefault(); // 防止默认行为
                });
            }
            if (layEvent == "del") {
                const index = $(obj.tr[0]).data("index");
                let list = table.cache["purchasePlanFormTable"].filter((v) => {
                    return v["LAY_TABLE_INDEX"] != index;
                });
                getNewTable(list,list.length)
                table.reload("purchasePlanFormTable", {
                    data: list
                });
            } else if (layEvent == "materialDetail") {
                // nowIndex = obj.tr.index()
                // var tableTwo
                // let zindex = admin.formOpen({
                //     area: "90%",
                //     offset: "10%",
                //     title: "选择物料",
                //     content: $("#warehouseMaterialRequisitionRecordForm").html(),
                //     success: function () {
                //         tableTwo = table.render({
                //             elem: "#warehouseMaterialRequisitionRecordTable",
                //             url: config.base + "warehouse/warehouse/productInventory/list?productStatus=3&customerId=" + customerId,
                //             where:searchData,
                //             page: true,
                //             cols: [
                //                 [
                //                     { type: "radio" },
                //                     { field: "userBundleCode", align: "center", title: "捆包号" },
                //                     { field: "productVariety", align: "center", title: "品种" },
                //                     { field: "productMark", align: "center", title: "牌号" },
                //                     { field: "productProducer", align: "center", title: "厂家" },
                //                     { field: "warehouseName", align: "center", title: "所在仓库" },
                //                     { field: "warehouseShelfSpaceCode", align: "center", title: "所在库位" },
                //                     { field: "productCode", align: "center", title: "客户成品料号" },
                //                     { field: "productSpecCode", align: "center", title: "规格" },
                //                     { field: "specThickness", align: "center", title: "厚度/壁厚/直径" },
                //                     { field: "specWidth", align: "center", title: "宽度/外径" },
                //                     { field: "specLength", align: "center", title: "长度" },
                //                     { field: "grossWeight", align: "center", title: "重量" },
                //                     { field: "productMainUnit", align: "center", title: "成品单位" },
                //                     // { field: "grossWeight", align: "center", title: "首入库时间" },
                //                 ]
                //             ]
                //         });
                //
                //     // admin.initDataSelect("enterprise/product/admin/productVariety/list", { limit: 9999 }, "productVariety", null, "品种", "varietyName", "varietyName");
                //     // admin.initDataSelect("enterprise/product/admin/productBrand/list", { limit: 9999 }, "productBrand", null, "品牌", "name", "name");
                //     // admin.initDataSelect("enterprise/product/admin/productMark/list", { limit: 9999 }, "productMark", null, "牌号", "markName", "markName");
                //     // admin.initDataSelect("enterprise/product/admin/productProducer/list", { limit: 9999 }, "productProducer", null, "生产商", "producerName", "producerName");
                //
                //         // 搜索
                //         form.on("submit(itemSubSearchTwo)", function (data) {
                //             tableTwo.reload({
                //                 where: {
                //                     ...data.field,
                //                 },
                //                 page: { curr: 1 }
                //             });
                //         });
                //
                //         // 重置搜索
                //         form.on("submit(itemResetsTwo)", function (data) {
                //             tableTwo.reload({
                //                 where: {
                //                     ...admin.resetSearch(data.field),
                //                 },
                //                 page: { curr: 1 }
                //             });
                //         });
                //     }
                // });
                //
                //
                // $("#saveMaterialInfo").click(() => {
                //     let list = table.cache["purchasePlanFormTable"];
                //     let list1 = table.checkStatus("warehouseMaterialRequisitionRecordTable").data;
                //
                //     let checkData = table.checkStatus("warehouseMaterialRequisitionRecordTable")
                //     let currentIndex = nowIndex;
                //
                //     if (currentIndex !== undefined && list[currentIndex]) {
                //         list[currentIndex].materialNumber = list1.map((v) => v.userBundleCode).join(",");
                //         list[currentIndex].sysBundleList = list1.map((v) => v.sysBundleCode).join(",");
                //     }
                //     table.reload("purchasePlanFormTable", {
                //         data: list
                //     });
                //     layer.close(zindex);
                // });
                // table.on("tool(warehouseMaterialRequisitionRecordTable)", function (obj) {
                //     var d = obj.data; // 获取当前行的数据
                //     var layEvent = obj.event; // 获取事件名（edit 或 del）
                //     if (layEvent == "del111") {
                //         const index = $(obj.tr[0]).data("index");
                //         let list = table.cache["warehouseMaterialRequisitionRecordTable"].filter((v) => {
                //             return v["LAY_TABLE_INDEX"] != index;
                //         });
                //         table.reload("warehouseMaterialRequisitionRecordTable", {
                //             data: list
                //         });
                //     }
                // });
            }
        });
        table.on("tool(warehouseProcessingDescription)", function (obj) {
            var d = obj.data; // 获取当前行的数据
            var layEvent = obj.event; // 获取事件名（edit 或 del）
            if (obj.tr) {
                obj.tr.on("click", function (e) {
                    e.preventDefault(); // 防止默认行为
                });
            }
            if (layEvent == "warehouseProcessingDescriptiondel") {
                const index = $(obj.tr[0]).data("index");
                let list = table.cache["warehouseProcessingDescription"].filter((v) => {
                    return v["LAY_TABLE_INDEX"] != index;
                });
                table.reload("warehouseProcessingDescription", {
                    data: list
                });
            }
        });
        function getNewTable(dataList,length){
            let materialNumber= table.cache["materialNumberFormTable"];
            let markId=materialNumber[0].markId
            let grossWeight=materialNumber[0].grossWeight
            let processId=$("#processingType").val()
            dataList.forEach(function (item,index){
                if(markId && processId && item.warehouseLength && item.diameter){
                    let formData={markId,processId,count:length,warehouseLength:item.warehouseLength,diameter:item.diameter}
                    admin.req(
                        "warehouse/warehouse/admin/productMark/computePrice",
                        formData,
                        function (res) {
                            layer.closeAll("loading");
                            if (res.code == 200) {
                                dataList[index].newPrice=res.data
                                dataList[index].price=res.data
                                if(item.packageMethod==='1'){
                                    dataList[index].price=Number(res.data)+10
                                    if(item.unitWeight && item.bundleQuantity){
                                        let num2=Number(item.unitWeight)*Number(item.bundleQuantity)*Number(Number(res.data)+10)
                                        dataList[index].subtotal=parseFloat(num2.toFixed(4))
                                    }
                                }else{
                                    if(item.unitWeight && item.bundleQuantity){
                                        let num2=Number(item.unitWeight)*Number(item.bundleQuantity)*Number(res.data)
                                        dataList[index].subtotal=parseFloat(num2.toFixed(4))
                                    }
                                }
                            } else {
                                dataList[index].newPrice=0
                                dataList[index].price=0
                                dataList[index].subtotal=0
                                // tableVal.reload({
                                //     data: dataList,
                                // });
                                layer.msg(res.msg, { icon: 2, time: 1000 });
                            }
                        },
                        "GET",
                        false,
                        "application/json"
                    );
                }
            })
            // console.log(grossWeight,dataList.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0),'333',grossWeight-dataList.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0))
            form.val("warehouseProductionOrderForm", {
                totalProcessingFee: dataList.reduce((acc, curr) => acc + (curr.subtotal || 0), 0),
                totalWeight: dataList.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0),
                materialType: parseFloat(grossWeight-dataList.reduce((acc, curr) => acc + (curr.theoreticalWeight || 0), 0)).toFixed(4),
            });
            return dataList
        }

        $("#Configure").click(function () {
            if ($("#customerId").val() && $("#userBundleCode").val() && $("#processingType").val()) {
                let codeOne = $("#userBundleCode").val()
                const newOriginalBundleCode = codeOne + '-' + bundleCodeCounter++;
                var dataList = table.cache["purchasePlanFormTable"] ? table.cache["purchasePlanFormTable"] : []
                let length=dataList.length+1
                if(length>0){
                  getNewTable(dataList,length)
                }
                dataList.push(
                    {
                        childBundle: newOriginalBundleCode,
                        productType:'',
                        productSpecCode:'',
                        diameter:'',
                        warehouseWidth:'',
                        warehouseLength:'',
                        // type:'',
                        packageMethod:'',
                        productMainUnit:'',
                        bundleQuantity:'',
                        unitWeight:0,
                        theoreticalWeight:0,
                        remark:'',
                        price:0,
                        subtotal:0,
                    }
                )

                table.reload("purchasePlanFormTable", {
                    data: dataList
                });


            } else {
                layer.msg("请选择加工方式、客户以及原始捆包号", { icon: 2, time: 1000 });
            }
        });
        $("#addWarehouseProcessingDescription").click(function (){
            if (nowData.eventName === "detail") {
                return;
            }
            admin.formOpen({
                area: "90%",
                offset: ['6%', '6%'],
                title: "选择加工工艺描述模板",
                path: "components/warehouse/product/warehouseProductionOrderSelect.html",
                success: function () {
                },
                end: function () {
                    if(childData.SelectList && childData.SelectList.length){
                        let data=childData.SelectList
                        let tableCont=table.cache["warehouseProcessingDescription"]
                        let json = data.concat(tableCont); //两个数组对象合并
                        let newJson = []; //盛放去重后数据的新数组
                        for(item1 of json){  //循环json数组对象的内容
                            let flag = true;  //建立标记，判断数据是否重复，true为不重复
                            for(item2 of newJson){  //循环新数组的内容
                                if(item1.id==item2.id){ //让json数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
                                    flag = false;
                                }
                            }
                            if(flag){ //判断是否重复
                                newJson.push(item1); //不重复的放入新数组。  新数组的内容会继续进行上边的循环。
                            }
                        }
                        table.reload("warehouseProcessingDescription", {
                            data: newJson
                        });
                    }
                }
            });
        })

        $("#warehouseProductionOrderForm .layui-table-body").css("overflow", "visible");
        $("#warehouseProductionOrderForm .layui-table-box").css("overflow", "visible");
        $("#warehouseProductionOrderForm .layui-table-view").css("overflow", "visible");
    });
</script>

<style>

    #warehouseProductionOrderForm .layui-form-label {
        width: 125px;
    }

    #warehouseProductionOrderForm .layui-input-block {
        margin-left: 155px;
    }

    #warehouseProductionOrderForm .layui-form-item .layui-inline {
        /* margin-bottom: 5px; */
        margin-right: 0px;
    }

    #warehouseProductionOrderForm .layui-table-cell {
        overflow: visible !important;
    }

    #table .layui-table-box {
        overflow: hidden !important;
    }

    #table .layui-table-body {
        overflow: auto !important;
    }
    #table .layui-table-view .layui-table td, .layui-table-view .layui-table th{
        overflow: hidden;
    }
    #form .layui-table-cell {
       padding: 0 6px;
    }


    .chooseCode {
        position: relative;
    }



        .mask {
            position: absolute;
            width: 100%;
            height: 100%;
            background: rgba(158, 157, 157, 0.1);
            top: 50%;
            left: 50%;
            z-index: 2;
            transform: translate(-50%, -50%);
        }
</style>